package com.hh.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
public class RedissonTest {
    public static void main(String[] args) {
        redissonTest();
//        getJedisClient();
    }

    private static void getJedisClient() {
        //创建一个数据库连接池对象（单例），需要指定服务的ip和端口号
//        JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(),"10.201.2.2", 6379,2000,"uCaUm6YOjh9OFyRl@2020#!");
        JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(),"localhost", 6379,2000,"root");
        //从连接池中获得连接
        Jedis jedis = jedisPool.getResource();
        //使用Jedis操作数据库（方法级别使用）
        String result = jedis.get("a");
        String key = UUID.randomUUID().toString();
        jedis.set(key, UUID.randomUUID().toString());
        System.out.println(result);
        //一定要关闭Jedis连接
        jedis.close();
        //系统关闭前关闭连接池
        jedisPool.close();
    }

    private static void redissonTest() {
        RedissonClient redissonClient = getRedissonClient();
        redissonClient.getBucket("name")
                .set("huanghuai");
        RLock l = redissonClient.getLock("l");
        new Thread(() -> l.lock(1, TimeUnit.DAYS)).start();

        try {
            Thread.sleep(500);
            l.lock();
            System.out.println(l.isLocked());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                l.unlock();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(1);
    }

    private static RedissonClient getRedissonClient() {
        Config config = new Config();
        config.setCodec(new StringCodec());
        config.useSingleServer().setAddress("redis://localhost:6379")
//                ;
                 .setPassword("root");
        return Redisson.create(config);
    }


}